<template>
  <div class="img-previewer" v-if="visible">
    <img
      class="preview-content"
      :src="url"
      onerror="this.src=''"
      alt="评论中的图片"
      @load="loadHandler"
    />
    <span class="previewer-close" @click="close"></span>
    <div class="mask" @click="close"></div>
  </div>
</template>

<script>
export default {
  name: "img-previewer",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    url: {
      type: String,
      default: "",
    },
  },
  watch: {
    visible(n) {
      document
        .querySelector("html")
        .classList[n ? "add" : "remove"]("disable-scroll");
    },
  },
  methods: {
    loadHandler(e) {
      const { width, height } = e.target;
      e.target.setAttribute(width >= height ? "width" : "height", "100%");
    },
    close() {
      this.$emit("update:visible", false);
    },
  },
};
</script>
<style lang="scss" scoped>
.img-previewer {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 150;
  .preview-content {
    position: absolute;
    z-index: 2;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%, -50%, 0);
    max-width: 100vw;
    max-height: 100vh;
  }
  .previewer-close {
    cursor: pointer;
    position: fixed;
    top: 14px;
    right: 14px;
    width: 40px;
    height: 40px;
    z-index: 3;
    background: url("")
      no-repeat center;
    background-size: cover;
  }
  .mask {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 1;
    backdrop-filter: blur(4px);
    background: rgba(0, 0, 0, 0.6);
  }
}
</style>